package repository

import (
	"gorm.io/gorm"
	"shyxy-model-agent/common/cache/lru"
	"shyxy-model-agent/core/model"
)

type onlineModelRepository struct {
	*BaseRepository
}

func NewOnlineModelRepository(db *gorm.DB) OnlineModelRepository {
	return &onlineModelRepository{
		BaseRepository: NewBaseRepository(db),
	}
}

func (omr *onlineModelRepository) Create(onlineModel *model.OnlineModel) error {
	return omr.GetDB().Create(onlineModel).Error
}

func (omr *onlineModelRepository) FindOneByModelInfoID(modelInfoID uint) (*model.OnlineModel, error) {
	var onlineModel model.OnlineModel
	err := omr.GetDB().Where("model_info_id = ?", modelInfoID).First(&onlineModel).Error
	if err != nil {
		return nil, err
	}
	return &onlineModel, nil
}

func (omr *onlineModelRepository) FindOneByModelInfoIDWithModelInfo(modelInfoID uint) (*model.OnlineModel, error) {
	var onlineModel model.OnlineModel
	err := omr.GetDB().Preload("ModelInfo").Where("model_info_id = ?", modelInfoID).First(&onlineModel).Error
	if err != nil {
		return nil, err
	}
	return &onlineModel, nil
}

func (omr *onlineModelRepository) DeleteByModelInfoID(modelInfoID uint) error {
	return omr.GetDB().Where("model_info_id = ?", modelInfoID).Delete(&model.OnlineModel{}).Error
}

type cachedOnlineModelRepository struct {
	*BaseCachedRepository
}

func (comr *cachedOnlineModelRepository) CachedRepository() {}

func NewCachedOnlineModelRepository(db *gorm.DB, cache *lru.LRU) OnlineModelRepository {
	return &cachedOnlineModelRepository{
		BaseCachedRepository: NewBaseCachedRepository(db, cache, "online_model"),
	}
}

func (comr *cachedOnlineModelRepository) Create(onlineModel *model.OnlineModel) error {
	return (&onlineModelRepository{BaseRepository: NewBaseRepository(comr.GetDB())}).Create(onlineModel)
}

func (comr *cachedOnlineModelRepository) FindOneByModelInfoID(modelInfoID uint) (*model.OnlineModel, error) {
	return (&onlineModelRepository{BaseRepository: NewBaseRepository(comr.GetDB())}).FindOneByModelInfoID(modelInfoID)
}

func (comr *cachedOnlineModelRepository) FindOneByModelInfoIDWithModelInfo(modelInfoID uint) (*model.OnlineModel, error) {
	return (&onlineModelRepository{BaseRepository: NewBaseRepository(comr.GetDB())}).FindOneByModelInfoIDWithModelInfo(modelInfoID)
}

func (comr *cachedOnlineModelRepository) DeleteByModelInfoID(modelInfoID uint) error {
	return (&onlineModelRepository{BaseRepository: NewBaseRepository(comr.GetDB())}).DeleteByModelInfoID(modelInfoID)
}

func NewOnlineModelRepositoryWithCache(db *gorm.DB, cache *lru.LRU) OnlineModelRepository {
	if cache != nil {
		return NewCachedOnlineModelRepository(db, cache)
	}
	return NewOnlineModelRepository(db)
}
